document.addEventListener('DOMContentLoaded', function() {
    // DOM元素引用
    const uploadArea = document.getElementById('uploadArea');
    const uploadText = document.getElementById('uploadText');
    const fileInput = document.getElementById('fileInput');
    const loading = document.getElementById('loading');
    const error = document.getElementById('error');
    const success = document.getElementById('success');
    const preview = document.getElementById('preview');
    const downloadWordBtn = document.getElementById('download-word-btn');
    const downloadExcelBtn = document.getElementById('download-excel-btn');
    const processExcelBtn = document.getElementById('process-excel-btn');
    const processReviewBtn = document.getElementById('process-review-btn');
    const fileTypeRadios = document.getElementsByName('fileType');
    const reviewUploadArea = document.getElementById('reviewUploadArea');
    const twoColumnUpload = document.getElementById('twoColumnUpload');
    const uploadWordBtn = document.getElementById('uploadWordBtn');
    const uploadExcelBtn = document.getElementById('uploadExcelBtn');
    const excelFileInput = document.getElementById('excelFileInput');
    const modelSelector = document.getElementById('modelSelector');
    const modelTypeSelect = document.getElementById('modelType');
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const featureDescription = document.getElementById('featureDescription');
    const featureText = document.getElementById('featureText');
    const featureItems = document.querySelectorAll('.feature-item');
    const workspaceContainer = document.getElementById('workspaceContainer');
    const reviewModeSelect = document.getElementById('reviewModeSelect');

    // 功能菜单配置
    const featureConfig = {
        // 可用的功能
        availableFeatures: [
            'home',    // 工作台
            'word',    // 文档生成Markdown
            'excel',   // 文档审核项生成
            'review',  // 文档AI审核
            'doccheck' // 文档完整性检查概览
        ],
        // 敬请期待的功能
        comingSoonFeatures: [
            'code_audit_gen',  // 代码审核项生成
            'code_audit',      // 代码AI审核
            'doc_to_code',     // 文档生成代码
            'code_to_doc'      // 代码补全文档
        ]
    };

    // 功能描述文本
    const featureDescriptions = {
        'home': '工作台首页，查看任务动态和系统公告',
        'word': '将设计文档转化为md格式，便于拷贝给方舟助手进行提问。',
        'excel': '将审核要点转化为高质量的结构化提示词，便于大模型审核。生成后增加了Prompt列，文件可直接用于【文档AI审核】功能。审核要点文档可以下载模板了解格式要求！',
        'review': '上传设计文档和带Prompt列的审核要点文档，选择适合的大模型进行检核。过程需要您耐心等待，最终检核结果会生成到结果文件中，供您下载查阅。<a href="javascript:void(0)" onclick="window.open(\'audit-manual.html\', \'文档AI审核功能使用手册\', \'width=1000,height=800,resizable=yes,scrollbars=yes\')" style="color:#6f42c1;text-decoration:underline;margin-left:10px;">查看使用手册</a>',
        'doccheck': '选择文档类型并上传设计文档，系统会自动检查文档章节结构的完整性，并识别关键标签。提供文档结构概览和缺失项分析，帮助您快速发现文档不足之处。',
        'code_audit_gen': '敬请期待！代码审核项生成功能正在开发中。',
        'code_audit': '敬请期待！代码AI审核功能正在开发中。',
        'doc_to_code': '敬请期待！文档生成代码功能正在开发中。',
        'code_to_doc': '敬请期待！代码补全文档功能正在开发中。'
    };
    
    // 全局变量
    let downloadUrl = '';
    let currentFileType = 'home'; // 默认显示首页
    let currentFileName = '';
    let tempFilePath = '';
    let uploadedFiles = {
        word: null,
        excel: null
    };
    let currentTaskId = null;
    let progressInterval = null;
    let currentBreadcrumb = '工作台';
    let progressPollCount = 0; // 添加轮询计数器
    const MAX_POLL_COUNT = 1200; // 设置最大轮询次数
    let eventSource = null; // 添加SSE事件源

    // 文档类型数据（从docscheme.md中获取）
    const docTypes = [
        '产品服务类',
        '员工渠道类',
        '外联服务类',
        '信创及云原生类',
        '客户渠道类',
        '数据分析与加工类'
    ];
    
    // 文档章节结构（从docscheme.md中获取）
    const docSections = [
        { id: 'background', name: '背景介绍', subsections: [
            { id: 'requirements', name: '需求项' },
            { id: 'designIdea', name: '设计思路' }
        ]},
        { id: 'impactAnalysis', name: '影响性分析' },
        { id: 'pageDesign', name: '页面设计' },
        { id: 'serviceDesign', name: '服务设计' },
        { id: 'batchDesign', name: '批处理设计' },
        { id: 'dbDesign', name: '数据库设计' },
        { id: 'datalineDesign', name: '数据线设计' },
        { id: 'exceptionDesign', name: '异常处理设计' },
        { id: 'paramDesign', name: '参数配置设计' },
        { id: 'securityDesign', name: '安全设计' },
        { id: 'testPoints', name: '测试要点' },
        { id: 'opsDesign', name: '运维设计' },
        { id: 'otherDesign', name: '其他设计' }
    ];
    
    // 关注标签（从docscheme.md中获取）
    const focusTags = [
        { id: 'account', name: '账务', icon: 'account_balance' },
        { id: 'payment', name: '支付', icon: 'payment' },
        { id: 'batch', name: '批量', icon: 'view_comfy' },
        { id: 'dataMigration', name: '数据迁移', icon: 'storage' },
        { id: 'paramInit', name: '参数初始化', icon: 'settings' },
        { id: 'SystemA', name: 'A类系统', icon: 'category' },
        { id: 'infoCreate', name: '信创改造', icon: 'device_hub' }
    ];
    
    // 初始化菜单交互
    function initializeMenu() {
        // 默认展开第一个一级菜单（文档审核）
        const firstCategory = document.querySelector('.category-item');
        if (firstCategory) {
            const submenu = firstCategory.querySelector('.submenu');
            const toggle = firstCategory.querySelector('.category-toggle');
            if (submenu && toggle) {
                submenu.classList.add('open');
                toggle.classList.add('open');
            }
        }

        // 为每个菜单项添加点击事件
        document.querySelectorAll('.submenu-item').forEach(item => {
            const input = item.querySelector('input[type="radio"]');
            if (input) {
                const featureType = input.value;
                
                // 设置data-feature属性
                item.setAttribute('data-feature', featureType);
                
                item.addEventListener('click', function() {
                    // 选中对应的radio
                    input.checked = true;
                    currentFileType = featureType;
                    resetUI();
                    
                    // 检查是否是"敬请期待"的功能
                    if (featureConfig.comingSoonFeatures.includes(featureType)) {
                        showComingSoonPage(featureType);
                        
                        // 更新面包屑
                        const menuText = item.querySelector('span:last-child').textContent;
                        updateBreadcrumb(menuText);
                    } else {
                        updateAcceptedFileTypes();
                        updateFeatureDescription();
                        
                        // 更新面包屑
                        const menuText = item.querySelector('span:last-child').textContent;
                        updateBreadcrumb(menuText);
                    }
                });
            }
        });

        // 为分类菜单添加展开/折叠功能
        document.querySelectorAll('.category-name').forEach(category => {
            category.addEventListener('click', function(e) {
                // 阻止事件冒泡
                e.stopPropagation();
                
                const parentItem = this.closest('.category-item');
                if (parentItem) {
                    // 切换子菜单的显示状态
                    const submenu = parentItem.querySelector('.submenu');
                    submenu.classList.toggle('open');
                    
                    // 切换箭头方向
                    const toggle = this.querySelector('.category-toggle');
                    toggle.classList.toggle('open');
                }
            });
        });
        
        // 工作台按钮点击事件
        const homeButton = document.getElementById('homeButton');
        if (homeButton) {
            homeButton.addEventListener('click', function() {
                resetUI();
                currentFileType = 'home';
                updateAcceptedFileTypes();
                updateBreadcrumb('工作台');
            });
        }
    }

    // 更新面包屑导航
    function updateBreadcrumb(text) {
        currentBreadcrumb = text;
        const breadcrumb = document.querySelector('.breadcrumb');
        if (breadcrumb) {
            breadcrumb.innerHTML = `<span class="breadcrumb-item">${text}</span>`;
        }
    }

    // 显示"敬请期待"页面
    function showComingSoonPage(featureType) {
        // 创建或获取"敬请期待"容器
        let comingSoonContainer = document.getElementById('comingSoonContainer');
        if (!comingSoonContainer) {
            comingSoonContainer = document.createElement('div');
            comingSoonContainer.id = 'comingSoonContainer';
            comingSoonContainer.className = 'feature-container';
            document.querySelector('.main-content').appendChild(comingSoonContainer);
        }
        
        // 隐藏其他所有功能区域
        if (workspaceContainer) workspaceContainer.style.display = 'none';
        if (uploadArea) uploadArea.style.display = 'none';
        if (twoColumnUpload) twoColumnUpload.style.display = 'none';
        if (featureDescription) featureDescription.style.display = 'block';
        if (modelSelector) modelSelector.style.display = 'none';
        
        // 显示功能描述
        if (featureText) {
            featureText.innerHTML = featureDescriptions[featureType] || '该功能正在开发中，敬请期待！';
        }
        
        // 更新"敬请期待"容器内容并显示
        comingSoonContainer.innerHTML = `
            <div class="coming-soon-content">
                <div class="coming-soon-icon">
                    <i class="material-icons">schedule</i>
                </div>
                <h2 class="coming-soon-title">敬请期待</h2>
                <p class="coming-soon-text">
                    您选择的功能 "${getFriendlyFeatureName(featureType)}" 正在开发中，敬请期待！
                </p>
            </div>
        `;
        comingSoonContainer.style.display = 'block';
    }
    
    // 根据featureType获取友好的功能名称
    function getFriendlyFeatureName(featureType) {
        const nameMap = {
            'code_audit_gen': '代码审核项生成',
            'code_audit': '代码AI审核',
            'doc_to_code': '文档生成代码',
            'code_to_doc': '代码补全文档'
        };
        return nameMap[featureType] || featureType;
    }

    // 切换功能项高亮
    function updateFeatureItemActive() {
        // 移除所有子菜单项的高亮
        document.querySelectorAll('.submenu-item').forEach(item => {
            item.classList.remove('active');
        });
        
        // 添加当前选中项的高亮
        const selectedRadio = document.querySelector(`input[name="fileType"][value="${currentFileType}"]`);
        if (selectedRadio) {
            const submenuItem = selectedRadio.closest('.submenu-item');
            if (submenuItem) {
                submenuItem.classList.add('active');
                
                // 确保父菜单是展开的
                const parentCategory = submenuItem.closest('.category-item');
                if (parentCategory) {
                    const toggle = parentCategory.querySelector('.category-toggle');
                    const submenu = parentCategory.querySelector('.submenu');
                    toggle.classList.add('open');
                    submenu.classList.add('open');
                }
            }
        }
    }

    function updateFeatureDescription() {
        // 更新功能描述文本
        featureText.innerHTML = featureDescriptions[currentFileType] || '';
    }

    function updateAcceptedFileTypes() {
        // 首先隐藏所有功能区域
        if (workspaceContainer) workspaceContainer.style.display = 'none';
        uploadArea.style.display = 'none';
        twoColumnUpload.style.display = 'none';
        featureDescription.style.display = 'none';
        modelSelector.style.display = 'none';
        progressContainer.style.display = 'none'; // 确保隐藏进度条和日志区域
        
        // 隐藏审核结果预览
        const resultsContainer = document.getElementById('reviewResultsContainer');
        if (resultsContainer) {
            resultsContainer.style.display = 'none';
        }
        
        // 隐藏文档完整性检查相关元素
        let docTypeSelector = document.getElementById('docTypeSelector');
        if (docTypeSelector) docTypeSelector.style.display = 'none';
        const docCheckResult = document.getElementById('docCheckResult');
        if (docCheckResult) docCheckResult.style.display = 'none';
        
        // 隐藏"敬请期待"容器
        const comingSoonContainer = document.getElementById('comingSoonContainer');
        if (comingSoonContainer) {
            comingSoonContainer.style.display = 'none';
        }

        // 隐藏完整性检查按钮
        const docCheckBtn = document.getElementById('docCheckBtn');
        if (docCheckBtn) {
            docCheckBtn.style.display = 'none';
        }

        if (currentFileType === 'home') {
            // 显示首页工作台
            if (workspaceContainer) workspaceContainer.style.display = 'block';
        } 
        else {
            // 显示功能描述
            featureDescription.style.display = 'block';
            
            if (currentFileType === 'word') {
                fileInput.accept = '.docx';
                uploadText.textContent = '拖拽Word文件到这里或点击选择文件';
                uploadArea.style.display = 'block';
                // 隐藏Excel模板下载按钮
                document.getElementById('templateDownloadBtn').style.display = 'none';
            } else if (currentFileType === 'excel') {
                fileInput.accept = '.xlsx';
                uploadText.textContent = '拖拽Excel文件到这里或点击选择文件';
                uploadArea.style.display = 'block';
                // 显示Excel模板下载按钮
                document.getElementById('templateDownloadBtn').style.display = 'block';
                // 对于Excel处理功能，显示模型选择器
                modelSelector.style.display = 'block';
            } else if (currentFileType === 'review') {
                // 在审核模式下，显示双栏上传，隐藏普通上传区域
                twoColumnUpload.style.display = 'flex';
                modelSelector.style.display = 'block';
                processReviewBtn.style.display = 'none'; // 初始设为隐藏，仅当两个文件都上传后才显示
                
                // 初始化审核模式选择框状态
                updateReviewModeUI();
            } else if (currentFileType === 'doccheck') {
                // 文档完整性检查功能
                // 显示文档类型选择器和上传区域
                if (!docTypeSelector) {
                    createDocTypeSelector();
                    docTypeSelector = document.getElementById('docTypeSelector');
                }
                docTypeSelector.style.display = 'block';
                fileInput.accept = '.docx';
                uploadText.textContent = '拖拽Word文件到这里或点击选择文件';
                uploadArea.style.display = 'block';
                
                // 创建检查按钮
                if (!document.getElementById('docCheckBtn')) {
                    const actionsDiv = document.querySelector('.actions');
                    const checkBtn = document.createElement('button');
                    checkBtn.id = 'docCheckBtn';
                    checkBtn.className = 'btn process-btn';
                    checkBtn.textContent = '完整性检查';
                    checkBtn.addEventListener('click', handleDocCheck);
                    checkBtn.style.display = 'none'; // 初始状态隐藏
                    actionsDiv.appendChild(checkBtn);
                }
            }
        }
    }

    function resetUI() {
        loading.style.display = 'none';
        error.style.display = 'none';
        success.style.display = 'none';
        preview.innerHTML = '';
        downloadWordBtn.style.display = 'none';
        downloadExcelBtn.style.display = 'none';
        processExcelBtn.style.display = 'none';
        processReviewBtn.style.display = 'none';
        progressContainer.style.display = 'none';
        modelSelector.style.display = 'none';
        
        // 隐藏审核结果预览
        const resultsContainer = document.getElementById('reviewResultsContainer');
        if (resultsContainer) {
            resultsContainer.style.display = 'none';
        }
        
        // 重置上传文本内容和样式
        if (uploadText) {
            if (currentFileType === 'word') {
                uploadText.textContent = '拖拽Word文件到这里或点击选择文件';
            } else if (currentFileType === 'excel') {
                uploadText.textContent = '拖拽Excel文件到这里或点击选择文件';
            } else if (currentFileType === 'doccheck') {
                uploadText.textContent = '拖拽Word文件到这里或点击选择文件';
            }
            uploadText.classList.remove('file-selected');
        }
        
        // 隐藏文档完整性检查相关元素
        let docTypeSelector = document.getElementById('docTypeSelector');
        if (docTypeSelector) docTypeSelector.style.display = 'none';
        const docCheckResult = document.getElementById('docCheckResult');
        if (docCheckResult) docCheckResult.style.display = 'none';
        
        // 隐藏"敬请期待"容器
        const comingSoonContainer = document.getElementById('comingSoonContainer');
        if (comingSoonContainer) {
            comingSoonContainer.style.display = 'none';
        }
        
        // 重置文件名
        const wordFileName = document.getElementById('wordFileName');
        const excelFileName = document.getElementById('excelFileName');
        if (wordFileName) wordFileName.textContent = '未选择';
        if (excelFileName) excelFileName.textContent = '未选择';
        
        // 重置日志区域
        const logArea = document.getElementById('logArea');
        if (logArea) {
            logArea.innerHTML = '等待日志信息...';
        }
        
        downloadUrl = '';
        currentFileName = '';
        tempFilePath = '';
        uploadedFiles.word = null;
        uploadedFiles.excel = null;
        
        // 重置轮询计数器
        progressPollCount = 0;
        
        // 停止任务进度轮询
        if (progressInterval) {
            clearInterval(progressInterval);
            progressInterval = null;
        }
    }

    // 拖拽事件处理
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, preventDefaults, false);
        document.body.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, unhighlight, false);
    });

    function highlight(e) {
        uploadArea.classList.add('dragover');
    }

    function unhighlight(e) {
        uploadArea.classList.remove('dragover');
    }

    uploadArea.addEventListener('drop', handleDrop, false);
    fileInput.addEventListener('change', handleFiles, false);
    downloadWordBtn.addEventListener('click', handleDownloadWord, false);
    downloadExcelBtn.addEventListener('click', handleDownloadExcel, false);
    processExcelBtn.addEventListener('click', handleProcessExcel, false);
    processReviewBtn.addEventListener('click', handleProcessReview, false);
    
    // 添加审核模式选择下拉框的事件监听器
    if (reviewModeSelect) {
        reviewModeSelect.addEventListener('change', updateReviewModeUI);
    }
    
    // 更新审核模式UI
    function updateReviewModeUI() {
        if (currentFileType !== 'review') return;
        
        const excelUploadColumn = excelFileInput.closest('.upload-column');
        const reviewMode = reviewModeSelect.value;
        
        if (reviewMode === 'baseAudit') {
            // 基础审核项模式：禁用Excel上传，自动显示处理按钮
            excelFileInput.disabled = true;
            uploadExcelBtn.disabled = true;
            excelUploadColumn.style.opacity = '0.5';
            document.getElementById('excelFileName').textContent = '使用基础审核项';
            
            // 如果Word已上传，启用处理按钮
            if (uploadedFiles.word) {
                processReviewBtn.style.display = 'block';
            }
        } else if (reviewMode === 'sdAudit') {
            // 实调审核项模式：禁用Excel上传，自动显示处理按钮
            excelFileInput.disabled = true;
            uploadExcelBtn.disabled = true;
            excelUploadColumn.style.opacity = '0.5';
            document.getElementById('excelFileName').textContent = '使用实调审核项';
            
            // 如果Word已上传，启用处理按钮
            if (uploadedFiles.word) {
                processReviewBtn.style.display = 'block';
            }
            
            // 显示实调审核项下载链接
            const downloadLink = document.querySelector('.upload-column a.download-btn');
            if (downloadLink) {
                downloadLink.href = '/download-audit-template-sd';
                downloadLink.textContent = '下载实调审核项模板';
            }
        } else {
            // 上传模式：启用Excel上传
            excelFileInput.disabled = false;
            uploadExcelBtn.disabled = false;
            excelUploadColumn.style.opacity = '1';
            
            // 重置Excel文件状态
            if (!uploadedFiles.excel) {
                document.getElementById('excelFileName').textContent = '未选择';
            }
            
            // 恢复正常下载链接
            const downloadLink = document.querySelector('.upload-column a.download-btn');
            if (downloadLink) {
                downloadLink.href = '/download-audit-template-with-prompt';
                downloadLink.textContent = '下载Excel模板';
            }
            
            // 只有当两个文件都上传时才显示处理按钮
            processReviewBtn.style.display = (uploadedFiles.word && uploadedFiles.excel) ? 'block' : 'none';
        }
    }

    // 文档审核上传处理
    document.getElementById('wordFileInput').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        uploadedFiles.word = file;
        document.getElementById('wordFileName').textContent = file.name;
        
        // 根据当前审核模式决定是否启用处理按钮
        if (reviewModeSelect.value === 'baseAudit' || (uploadedFiles.word && uploadedFiles.excel)) {
            processReviewBtn.style.display = 'block';
        }
    });
    
    document.getElementById('excelFileInput').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        uploadedFiles.excel = file;
        document.getElementById('excelFileName').textContent = file.name;
        
        // 如果两个文件都已上传，启用处理按钮
        if (uploadedFiles.word && uploadedFiles.excel) {
            processReviewBtn.style.display = 'block';
        }
    });

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles({ files: files });
    }

    function handleFiles(e) {
        const file = e.target ? e.target.files[0] : (e.files ? e.files[0] : null);
        if (!file) return;

        if (currentFileType === 'word' && !file.name.endsWith('.docx')) {
            showError('请选择.docx格式的Word文件');
            return;
        }

        if (currentFileType === 'excel' && !file.name.endsWith('.xlsx')) {
            showError('请选择.xlsx格式的Excel文件');
            return;
        }
        
        if (currentFileType === 'doccheck' && !file.name.endsWith('.docx')) {
            showError('请选择.docx格式的Word文件');
            return;
        }

        resetUI();
        currentFileName = file.name;
        
        // 直接更新上传区域的提示文字为文件名
        if (uploadText) {
            uploadText.textContent = `已选择: ${file.name}`;
            // 添加文件名样式
            uploadText.classList.add('file-selected');
        }
        
        if (currentFileType === 'doccheck') {
            // 保存文件引用，并显示完整性检查按钮
            uploadedFiles.docCheck = file;
            document.getElementById('docCheckBtn').style.display = 'block';
            showSuccess(`已上传: ${file.name}`);
            
            // 确保文档类型选择器保持可见
            const docTypeSelector = document.getElementById('docTypeSelector');
            if (docTypeSelector) docTypeSelector.style.display = 'block';
            
            return;
        }
        
        uploadFile(file);
    }

    function uploadFile(file) {
        const formData = new FormData();
        formData.append('file', file);
        currentFileName = file.name;

        loading.style.display = 'block';

        fetch('/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                throw new Error(data.error);
            }
            
            if (currentFileType === 'word') {
                // Word处理逻辑
                preview.innerHTML = data.content;
                
                // 显示下载按钮和相关信息
                if (data.markdown && data.markdown.path) {
                    downloadUrl = data.markdown.path;
                    downloadWordBtn.style.display = 'block';
                    
                    // 更新统计卡片
                    document.querySelector('.stats-container .stat-card:nth-child(1) .stat-value').textContent = 
                        (parseInt(document.querySelector('.stats-container .stat-card:nth-child(1) .stat-value').textContent) + 1).toString();
                }
            } else if (currentFileType === 'excel') {
                // Excel处理逻辑
                showSuccess('Excel文件上传成功，点击生成Prompt按钮开始处理');
                processExcelBtn.style.display = 'block';
                currentFileName = data.filename;
                tempFilePath = data.tempPath;
                
                // 确保模型选择器在Excel上传成功后可见
                if (modelSelector) {
                    modelSelector.style.display = 'block';
                }
            }
        })
        .catch(err => {
            showError(err.message || '处理过程中发生错误');
        })
        .finally(() => {
            loading.style.display = 'none';
        });
    }

    function handleDownloadWord() {
        if (downloadUrl) {
            window.location.href = downloadUrl;
        }
    }

    function handleDownloadExcel() {
        if (downloadUrl) {
            window.location.href = downloadUrl;
        }
    }

    function handleProcessExcel() {
        if (!currentFileName) {
            showError('请先上传Excel文件');
            return;
        }
        
        // 重置日志区域
        const logArea = document.getElementById('logArea');
        if (logArea) {
            logArea.innerHTML = '等待日志信息...';
        }
        
        loading.style.display = 'block';
        error.style.display = 'none';
        success.style.display = 'none';
        downloadExcelBtn.style.display = 'none';
        processExcelBtn.disabled = true; // 禁用处理按钮，防止重复点击
        
        // 获取选择的模型类型
        const modelType = document.getElementById('modelType').value;
        
        // 显示进度条和日志区域
        progressContainer.style.display = 'block';
        progressBar.style.width = '0%';
        progressText.textContent = '已完成: 0%';
        
        // 发送请求处理Excel文件
        fetch('/process-excel', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                filename: currentFileName,
                tempPath: tempFilePath,
                modelType: modelType // 添加模型类型参数
            })
        })
        .then(response => {
            // 创建一个新的ReadableStream，用于处理流式响应
            const reader = response.body.getReader();
            let decoder = new TextDecoder();
            let buffer = '';
            
            // 使用递归函数处理流式数据
            function readStream() {
                return reader.read().then(({ done, value }) => {
                    if (done) {
                        // 处理缓冲区中可能的剩余数据
                        if (buffer.length > 0) {
                            try {
                                const data = JSON.parse(buffer);
                                processExcelStreamUpdate(data);
                            } catch (e) {
                                console.error('解析剩余JSON响应失败:', e);
                            }
                        }
                        
                        return;
                    }
                    
                    // 将新的数据块添加到缓冲区
                    buffer += decoder.decode(value, { stream: true });
                    
                    // 尝试从缓冲区提取完整的JSON对象
                    let jsonStartIndex = 0;
                    try {
                        // 尝试解析整个缓冲区
                        const data = JSON.parse(buffer);
                        processExcelStreamUpdate(data);
                        // 清空缓冲区
                        buffer = '';
                    } catch (e) {
                        // JSON解析可能失败，因为数据不完整或者包含多个JSON对象
                        // 尝试逐行解析，查找完整的JSON对象
                        const lines = buffer.split('\n');
                        let validJSON = '';
                        
                        for (let i = 0; i < lines.length; i++) {
                            try {
                                if (lines[i].trim()) {
                                    const data = JSON.parse(lines[i]);
                                    processExcelStreamUpdate(data);
                                    // 移除已处理的行
                                    jsonStartIndex = buffer.indexOf(lines[i]) + lines[i].length + 1;
                                }
                            } catch (e) {
                                // 这一行不是完整的JSON，继续
                            }
                        }
                        
                        // 保留未能成功解析的部分
                        if (jsonStartIndex > 0) {
                            buffer = buffer.substring(jsonStartIndex);
                        }
                    }
                    
                    // 递归调用以读取更多数据
                    return readStream();
                });
            }
            
            // 开始读取流
            return readStream();
        })
        .catch(err => {
            showError(err.message || '处理Excel文件过程中发生错误');
            processExcelBtn.disabled = false; // 重新启用处理按钮
            loading.style.display = 'none';
        });
    }

    // 处理Excel流式更新
    function processExcelStreamUpdate(data) {
        // 隐藏loading状态
        loading.style.display = 'none';
        
        // 更新日志区域
        if (data.logs && Array.isArray(data.logs)) {
            // 确保日志更新仅添加新的日志行
            updateLogArea(data.logs);
        } else if (data.log) {
            // 支持单行日志格式
            updateLogArea([data.log]);
        }
        
        // 更新进度条
        if (data.total > 0 && typeof data.completed !== 'undefined') {
            const percent = data.percent || Math.round((data.completed / data.total) * 100);
            progressBar.style.width = `${percent}%`;
            progressText.textContent = `已完成: ${data.completed}/${data.total} (${percent}%)`;
        }
        
        // 根据处理状态更新UI
        if (data.status === 'completed') {
            // 处理完成
            showSuccess(data.message || 'Excel文件处理成功，可下载结果文件');
            processExcelBtn.disabled = false;
            
            if (data.download_path) {
                downloadUrl = data.download_path;
                downloadExcelBtn.style.display = 'block';
            }
            
            // 更新统计卡片
            document.querySelector('.stats-container .stat-card:nth-child(2) .stat-value').textContent = 
                (parseInt(document.querySelector('.stats-container .stat-card:nth-child(2) .stat-value').textContent) + 1).toString();
        } else if (data.status === 'failed') {
            // 处理失败
            showError(data.error || '处理Excel文件过程中发生错误');
            processExcelBtn.disabled = false;
        }
    }

    function handleProcessReview() {
        const wordFile = document.getElementById('wordFileInput').files[0];
        const reviewMode = reviewModeSelect.value;
        const modelType = document.getElementById('modelType').value;
        
        // 检查是否有Word文件
        if (!wordFile) {
            showError('请先上传Word文件');
            return;
        }
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('wordFile', wordFile);
        formData.append('modelType', modelType);
        
        // 根据审核模式确定Excel文件
        if (reviewMode === 'baseAudit') {
            // 使用基础审核项模式，添加标记
            formData.append('useBaseAudit', 'true');
        } else if (reviewMode === 'sdAudit') {
            // 使用实调审核项模式，添加标记
            formData.append('useSDTemplateAudit', 'true');
        } else {
            // 上传审核项模式，检查是否上传了Excel文件
            const excelFile = document.getElementById('excelFileInput').files[0];
            if (!excelFile) {
                showError('请先上传Excel审核项文件');
                return;
            }
            formData.append('excelFile', excelFile);
        }
        
        // 重置日志区域
        const logArea = document.getElementById('logArea');
        if (logArea) {
            logArea.innerHTML = '等待日志信息...';
        }
        
        // 显示加载状态
        loading.style.display = 'block';
        error.style.display = 'none';
        success.style.display = 'none';
        processReviewBtn.disabled = true;
        
        // 调用服务器端的审核API
        fetch('/process-review', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.error || '文档审核失败');
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.taskId) {
                // 任务已开始，显示进度条
                loading.style.display = 'none';
                progressContainer.style.display = 'block';
                showSuccess('审核任务已开始，请等待完成');
                
                // 存储任务ID并开始轮询进度
                currentTaskId = data.taskId;
                startProgressPolling(currentTaskId);
                
                // 更新统计卡片
                document.querySelector('.stats-container .stat-card:nth-child(3) .stat-value').textContent = 
                    (parseInt(document.querySelector('.stats-container .stat-card:nth-child(3) .stat-value').textContent) + 1).toString();
                document.querySelector('.stats-container .stat-card:nth-child(4) .stat-value').textContent = 
                    (parseInt(document.querySelector('.stats-container .stat-card:nth-child(4) .stat-value').textContent) + 1).toString();
            } else {
                showError('启动审核任务失败，服务器未返回任务ID');
                processReviewBtn.disabled = false;
            }
        })
        .catch(error => {
            loading.style.display = 'none';
            showError(error.message);
            processReviewBtn.disabled = false;
        });
    }
    
    // 开始轮询进度
    function startProgressPolling(taskId) {
        // 重置计数器
        progressPollCount = 0;
        currentTaskId = taskId;
        
        // 确保日志区域被重置
        const logArea = document.getElementById('logArea');
        if (logArea) {
            logArea.innerHTML = '等待日志信息...';
        }
        
        // 初始化审核结果表格容器
        initResultsTable();
        
        // 建立SSE连接
        connectEventSource(taskId);
        
        // 立即查询一次进度
        checkProgress(taskId);
        
        // 设置定时器，每2秒查询一次进度
        progressInterval = setInterval(() => {
            checkProgress(taskId);
        }, 2000);
    }
    
    // 连接SSE事件源
    function connectEventSource(taskId) {
        // 先关闭现有的连接
        if (eventSource) {
            eventSource.close();
            eventSource = null;
        }
        
        // 创建新的事件源连接
        eventSource = new EventSource(`/review-events/${taskId}`);
        
        // 连接建立事件
        eventSource.addEventListener('connected', function(event) {
            console.log('SSE连接已建立:', event.data);
        });
        
        // 初始化审核项列表事件
        eventSource.addEventListener('init_items', function(event) {
            const items = JSON.parse(event.data);
            console.log('收到初始化审核项:', items.length);
            
            // 初始化所有审核项的表格行
            if (Array.isArray(items) && items.length > 0) {
                items.forEach(item => {
                    // 为每个审核项创建一个初始状态的行
                    updateResultTableRow(item, true);
                });
            }
        });
        
        // 审核项更新事件
        eventSource.addEventListener('item_update', function(event) {
            const data = JSON.parse(event.data);
            updateResultTableRow(data, false);
        });
        
        // 错误处理
        eventSource.onerror = function(error) {
            console.error('SSE连接错误:', error);
            // 尝试重新连接
            setTimeout(() => {
                if (eventSource && eventSource.readyState === EventSource.CLOSED) {
                    connectEventSource(taskId);
                }
            }, 3000);
        };
    }
    
    // 新增：获取初始化审核项列表，用于任务启动时立即显示
    function getInitialItems(taskId, callback) {
        fetch(`/review-progress/${taskId}`)
            .then(response => response.json())
            .then(data => {
                if (data && data.initItems && data.initItems.length > 0) {
                    callback(data.initItems);
                }
            })
            .catch(err => {
                console.error('获取初始化审核项失败:', err);
            });
    }
    
    // 新增：初始化审核结果表格
    function initResultsTable() {
        // 检查是否已存在结果表格
        let resultsContainer = document.getElementById('reviewResultsContainer');
        
        // 如果不存在，创建一个
        if (!resultsContainer) {
            resultsContainer = document.createElement('div');
            resultsContainer.id = 'reviewResultsContainer';
            resultsContainer.className = 'review-results-container';
            
            // 创建表格标题
            const titleElement = document.createElement('h3');
            titleElement.textContent = '审核结果实时预览';
            resultsContainer.appendChild(titleElement);
            
            // 创建表格
            const table = document.createElement('table');
            table.id = 'resultsTable';
            table.className = 'results-table';
            
            // 添加表头
            table.innerHTML = `
                <thead>
                    <tr>
                        <th>审核类别</th>
                        <th>审核检查点</th>
                        <th>审核结论</th>
                        <th>审核结果</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;
            
            resultsContainer.appendChild(table);
            
            // 将容器添加到页面
            // 修改：将结果表格放在"操作"区域的下方（即下载按钮下方）
            const actionsDiv = document.querySelector('.actions');
            actionsDiv.parentNode.insertBefore(resultsContainer, actionsDiv.nextSibling);
        } else {
            // 使审核结果表格可见
            resultsContainer.style.display = 'block';
            // 清空表格内容，准备接收新的审核结果
            const tbody = document.querySelector('#resultsTable tbody');
            tbody.innerHTML = '';
        }
        
        // 如果已有任务ID，尝试立即获取初始化项目并显示
        if (currentTaskId) {
            getInitialItems(currentTaskId, (items) => {
                if (Array.isArray(items) && items.length > 0) {
                    items.forEach(item => {
                        // 为每个审核项创建一个初始状态的行
                        updateResultTableRow(item, true);
                    });
                }
            });
        }
    }
    
    // 更新结果表格中的行
    function updateResultTableRow(data, isInitializing = false) {
        const tbody = document.querySelector('#resultsTable tbody');
        if (!tbody) return; // 如果表格不存在，直接返回
        
        // 查找是否已存在该行
        let row = tbody.querySelector(`tr[data-item-id="${data.itemId}"]`);
        
        // 截断文本的辅助函数
        const truncateText = (text, maxLength = 40) => {
            if (!text || text.length <= maxLength) return text;
            return text.substring(0, maxLength) + '...';
        };
        
        // 如果行不存在，创建一个新行
        if (!row) {
            row = document.createElement('tr');
            row.setAttribute('data-item-id', data.itemId);
            
            // 获取文本并截断
            const category = data.category || '未知类别';
            const checkPoint = data.checkPoint || '';
            const truncatedCheckPoint = truncateText(checkPoint);
            
            // 初始化行内容
            row.innerHTML = `
                <td>${category}</td>
                <td title="${checkPoint}">${truncatedCheckPoint}</td>
                <td class="conclusion"></td>
                <td class="result">处理中...</td>
            `;
            
            tbody.appendChild(row);
        }
        
        // 更新行内容
        row.querySelector('td:nth-child(1)').textContent = data.category || '未知类别';
        const checkPointCell = row.querySelector('td:nth-child(2)');
        const checkPoint = data.checkPoint || '';
        checkPointCell.textContent = truncateText(checkPoint);
        checkPointCell.title = checkPoint; // 设置title属性以显示完整文本
        
        // 只有在不是初始化状态或明确有结论时才更新结论和结果
        if (!isInitializing || data.conclusion) {
            // 更新结论单元格，添加图标
            const conclusionCell = row.querySelector('.conclusion');
            
            // 根据结论类型设置图标和颜色
            if (data.conclusion === 'pass') {
                conclusionCell.innerHTML = '<span class="conclusion-icon pass">✓</span>通过';
            } else if (data.conclusion === 'warn') {
                conclusionCell.innerHTML = '<span class="conclusion-icon warn">⚠</span>警告';
            } else if (data.conclusion === 'fail') {
                conclusionCell.innerHTML = '<span class="conclusion-icon fail">✗</span>不通过';
            } else if (data.conclusion === 'notApplicable') {
                conclusionCell.innerHTML = '<span class="conclusion-icon not-applicable">-</span>不涉及';
            } else if (data.conclusion === 'processing') {
                conclusionCell.innerHTML = '<span class="conclusion-icon processing">○</span>处理中';
            } else {
                conclusionCell.innerHTML = '<span class="conclusion-icon waiting">?</span>待处理';
            }
            
            // 如果有结果，更新结果单元格
            if (data.result) {
                row.querySelector('.result').textContent = data.result;
            }
        } else {
            // 初始化状态，显示待处理
            const conclusionCell = row.querySelector('.conclusion');
            conclusionCell.innerHTML = '<span class="conclusion-icon waiting">?</span>待处理';
        }
    }
    
    // 检查进度
    function checkProgress(taskId) {
        // 增加计数器并检查是否超过最大调用次数
        progressPollCount++;
        if (progressPollCount > MAX_POLL_COUNT) {
            // 超过最大调用次数，停止轮询
            clearInterval(progressInterval);
            progressInterval = null;
            
            // 显示错误消息
            showError(`审核任务查询超时: 已达到最大查询次数(${MAX_POLL_COUNT}次)，请检查任务状态或重试`);
            processReviewBtn.disabled = false;
            return;
        }
        
        fetch(`/review-progress/${taskId}`)
            .then(response => response.json())
            .then(data => {
                // 更新进度条
                const percent = data.total > 0 ? Math.round((data.completed / data.total) * 100) : 0;
                progressBar.style.width = `${percent}%`;
                progressText.textContent = `已完成: ${data.completed}/${data.total} (${percent}%)`;
                
                // 更新日志文本框
                updateLogArea(data.logs || []);
                
                // 检查任务是否完成
                if (data.status === 'completed') {
                    // 停止轮询
                    clearInterval(progressInterval);
                    progressInterval = null;
                    
                    // 关闭SSE连接
                    if (eventSource) {
                        eventSource.close();
                        eventSource = null;
                    }
                    
                    // 显示成功消息和下载按钮
                    showSuccess(data.message || '文档审核完成');
                    downloadUrl = data.downloadPath;
                    downloadExcelBtn.style.display = 'inline-block';
                    processReviewBtn.disabled = false;
                } else if (data.status === 'failed') {
                    // 停止轮询
                    clearInterval(progressInterval);
                    progressInterval = null;
                    
                    // 关闭SSE连接
                    if (eventSource) {
                        eventSource.close();
                        eventSource = null;
                    }
                    
                    // 显示错误消息
                    showError(`审核任务失败: ${data.error || '未知错误'}`);
                    processReviewBtn.disabled = false;
                }
            })
            .catch(err => {
                console.error('检查进度出错:', err);
                // 记录错误但不要停止轮询，除非达到最大次数限制
            });
    }
    
    // 更新日志区域
    function updateLogArea(logs) {
        if (!logs || !Array.isArray(logs) || logs.length === 0) return;
        
        const logArea = document.getElementById('logArea');
        
        // 检查是否为新任务的第一批日志
        // 如果是等待日志信息或日志长度小于已显示的日志，则认为是新任务
        if (logArea.textContent === '等待日志信息...' || 
            (logs.length < logArea.innerHTML.split('<br>').filter(l => l.trim().length > 0).length)) {
            // 清空日志区域，准备显示新任务的日志
            logArea.innerHTML = '';
            
            // 直接添加所有日志
            const coloredLogs = logs.map(log => {
                // 添加颜色类
                if (log.includes('[INFO]')) {
                    return `<span class="log-info">${log}</span>`;
                } else if (log.includes('[ERROR]')) {
                    return `<span class="log-error">${log}</span>`;
                } else if (log.includes('[WARN]')) {
                    return `<span class="log-warn">${log}</span>`;
                } else if (log.includes('[SUCCESS]')) {
                    return `<span class="log-success">${log}</span>`;
                }
                return log;
            });
            
            logArea.innerHTML = coloredLogs.join('<br>');
        } else {
            // 获取已显示的日志行数
            const displayedLogs = logArea.innerHTML.split('<br>').filter(l => l.trim().length > 0);
            
            // 仅添加新的日志行
            const newLogs = logs.slice(displayedLogs.length);
            
            if (newLogs.length > 0) {
                // 应用日志级别的颜色
                const coloredLogs = newLogs.map(log => {
                    // 添加颜色类
                    if (log.includes('[INFO]')) {
                        return `<span class="log-info">${log}</span>`;
                    } else if (log.includes('[ERROR]')) {
                        return `<span class="log-error">${log}</span>`;
                    } else if (log.includes('[WARN]')) {
                        return `<span class="log-warn">${log}</span>`;
                    } else if (log.includes('[SUCCESS]')) {
                        return `<span class="log-success">${log}</span>`;
                    }
                    return log;
                });
                
                // 添加新日志
                if (logArea.innerHTML.length > 0) {
                    logArea.innerHTML += '<br>' + coloredLogs.join('<br>');
                } else {
                    logArea.innerHTML = coloredLogs.join('<br>');
                }
            }
        }
        
        // 滚动到底部
        logArea.scrollTop = logArea.scrollHeight;
    }

    function showError(message) {
        error.textContent = message;
        error.style.display = 'block';
        loading.style.display = 'none';
        
        // 如果是Excel处理功能，确保保持模型选择器显示
        if (currentFileType === 'excel') {
            if (modelSelector) modelSelector.style.display = 'block';
        }
        
        // 如果是文档完整性检查功能，确保保持选择器显示
        if (currentFileType === 'doccheck') {
            const docTypeSelector = document.getElementById('docTypeSelector');
            if (docTypeSelector) docTypeSelector.style.display = 'block';
        }
    }

    function showSuccess(message) {
        success.textContent = message;
        success.style.display = 'block';
        
        // 如果是Excel处理功能，确保保持模型选择器显示
        if (currentFileType === 'excel') {
            if (modelSelector) modelSelector.style.display = 'block';
        }
        
        // 如果是文档完整性检查功能，确保保持选择器显示
        if (currentFileType === 'doccheck') {
            const docTypeSelector = document.getElementById('docTypeSelector');
            if (docTypeSelector) docTypeSelector.style.display = 'block';
        }
    }

    // 切换聊天窗口显示/隐藏
    window.toggleChatWindow = function() {
        const chatWindow = document.getElementById('chatWindow');
        chatWindow.classList.toggle('open');
    }

    // 发送消息
    window.sendMessage = function() {
        const input = document.getElementById('messageInput');
        const message = input.value.trim();
        
        if (message) {
            // 清空输入框
            input.value = '';
            
            // 添加用户消息
            const chatMessages = document.querySelector('.chat-messages');
            chatMessages.innerHTML += `
                <div class="message user">
                    <div class="message-content">${message}</div>
                </div>
            `;
            
            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
            
            // 模拟助手回复
            setTimeout(() => {
                chatMessages.innerHTML += `
                    <div class="message assistant">
                        <div class="message-content">这是一个静态演示，实际开发中这里会连接到后端AI服务获取回复。</div>
                    </div>
                `;
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }, 1000);
        }
    }
    
    // 功能导航点击事件
    window.showFeatureDescription = function(featureType) {
        // 选中对应的radio按钮
        const radio = document.querySelector(`input[name="fileType"][value="${featureType}"]`);
        if (radio) {
            // 模拟点击对应的菜单项
            const submenuItem = radio.closest('.submenu-item');
            if (submenuItem) {
                submenuItem.click();
            }
        }
    }

    // 创建文档类型选择器
    function createDocTypeSelector() {
        // 创建选择器容器
        const docTypeSelector = document.createElement('div');
        docTypeSelector.id = 'docTypeSelector';
        docTypeSelector.className = 'doc-type-selector';
        
        // 创建文档类型和模型类型的双列布局
        const selectorHTML = `
            <div class="selector-row">
                <div class="selector-column">
                    <p>选择文档类型:</p>
                    <select id="docTypeSelect" class="model-select">
                        ${docTypes.map(type => `<option value="${type}">${type}</option>`).join('')}
                    </select>
                </div>
                <div class="selector-column">
                    <p>选择大模型:</p>
                    <select id="docModelSelect" class="model-select">
                    <option value="DeepSeek-R1-671B_20250302">建行方舟满血版R1（高质量）</option>
                    <option value="DeepSeek-R1-QW32B_SFT_0228_V1" selected>建行方舟蒸馏版（高响应）</option>
                    <option value="deepseek-reasoner">公网Deepseek R1</option>
                    </select>
                </div>
            </div>
        `;
        
        docTypeSelector.innerHTML = selectorHTML;
        
        // 添加到主内容区域
        document.querySelector('.main-content').appendChild(docTypeSelector);
        
        // 创建结果容器
        const docCheckResult = document.createElement('div');
        docCheckResult.id = 'docCheckResult';
        docCheckResult.className = 'doc-check-result';
        docCheckResult.style.display = 'none';
        document.querySelector('.main-content').appendChild(docCheckResult);
        
        return docTypeSelector;
    }
    
    // 处理文档完整性检查
    function handleDocCheck() {
        if (!uploadedFiles.docCheck) {
            showError('请先上传Word文档');
            return;
        }
        
        const docType = document.getElementById('docTypeSelect').value;
        const modelType = document.getElementById('docModelSelect').value;
        
        // 显示加载状态
        loading.style.display = 'block';
        error.style.display = 'none';
        success.style.display = 'none';
        document.getElementById('docCheckBtn').disabled = true;
        
        // 显示结果容器
        const resultContainer = document.getElementById('docCheckResult');
        resultContainer.style.display = 'block';
        resultContainer.innerHTML = `
            <div class="doc-check-container">
                <div class="doc-check-report full-width">
                    <div class="loading-message">正在处理中，请稍候...</div>
                </div>
            </div>
        `;
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('wordFile', uploadedFiles.docCheck);
        formData.append('docType', docType);
        formData.append('modelType', modelType);
        
        // 调用服务器端的文档完整性检查API
        fetch('/doc-completeness-check', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw new Error(data.error || '文档完整性检查失败');
                });
            }
            return response.json();
        })
        .then(data => {
            // 显示检查结果
            displayDocCheckResult(data);
            document.getElementById('docCheckBtn').disabled = false;
            loading.style.display = 'none';
        })
        .catch(error => {
            loading.style.display = 'none';
            showError(error.message);
            document.getElementById('docCheckBtn').disabled = false;
        });
    }

    // 显示文档完整性检查结果
    function displayDocCheckResult(data) {
        const resultContainer = document.getElementById('docCheckResult');
        resultContainer.style.display = 'block';
        
        if (!data) {
            resultContainer.innerHTML = '<div class="error">检查结果数据有误</div>';
            return;
        }
        
        // 如果返回了HTML内容
        if (data.htmlContent) {
            resultContainer.innerHTML = `
                <div class="doc-check-container">
                    <div class="doc-check-report full-width">
                        ${data.htmlContent}
                    </div>
                </div>
                <div class="report-actions">
                    <a href="${data.htmlReport}" target="_blank" class="btn">在新窗口查看报告</a>
                </div>
            `;
            return;
        }
        
        // 下面是原来的代码，如果没有HTML内容就回退到旧的方式显示
        if (!data.sections || !data.tags) {
            resultContainer.innerHTML = '<div class="error">检查结果数据有误</div>';
            return;
        }
        
        // 创建HTML内容
        let html = `
            <div class="result-header">
                <h2>文档完整性检查报告</h2>
                <p>文件名: ${currentFileName}</p>
                <p>文档类型: ${data.docType}</p>
                ${data.totalscore ? `<p>整体评分: <span class="score ${getScoreClass(data.totalscore)}">${data.totalscore}</span></p>` : ''}
            </div>
            
            <div class="result-sections">
                <h3>章节完整性检查</h3>
                <div class="section-grid">
        `;
        
        // 添加章节完整性结果
        data.sections.forEach(section => {
            const statusIcon = getStatusIcon(section.status);
            html += `
                <div class="section-item">
                    <div class="section-status">
                        <i class="material-icons">${statusIcon}</i>
                    </div>
                    <div class="section-info">
                        <div class="section-name">${section.name}</div>
                        <div class="section-score">完整性: <span class="score">${section.score || '-'}</span></div>
                        <div class="section-desc">${section.description || ''}</div>
                    </div>
                </div>
            `;
        });
        
        html += `
                </div>
            </div>
            
            <div class="result-tags">
                <h3>关注标签识别</h3>
                <div class="tag-container">
        `;
        
        // 添加标签识别结果
        data.tags.forEach(tag => {
            html += `
                <div class="tag-item ${tag.related ? 'related' : ''}">
                    <i class="material-icons">${getTagIcon(tag.name)}</i>
                    <span>${tag.name}</span>
                    ${tag.related ? '<div class="tag-indicator"></div>' : ''}
                </div>
            `;
        });
        
        html += `
                </div>
            </div>
            
            <div class="result-summary">
                <h3>总结</h3>
                <p>${data.summary || '文档完整性检查完成。'}</p>
            </div>
        `;
        
        resultContainer.innerHTML = html;
    }
    
    // 获取评分的CSS类
    function getScoreClass(score) {
        const scoreNum = parseInt(score);
        if (isNaN(scoreNum)) return '';
        
        if (scoreNum >= 70) {
            return 'score-high';
        } else if (scoreNum >= 40) {
            return 'score-medium';
        } else {
            return 'score-low';
        }
    }
    
    // 根据状态获取对应的图标
    function getStatusIcon(status) {
        switch(status) {
            case 'complete':
                return 'check_circle';
            case 'incomplete':
                return 'error_outline';
            case 'missing':
                return 'cancel';
            default:
                return 'help_outline';
        }
    }
    
    // 根据标签名获取对应的图标
    function getTagIcon(tagName) {
        const tag = focusTags.find(t => t.name === tagName);
        return tag ? tag.icon : 'label';
    }

    // 初始化界面
    initializeMenu();

    // 点击导航菜单项
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', function() {
            // 隐藏审核结果预览
            const resultsContainer = document.getElementById('reviewResultsContainer');
            if (resultsContainer) {
                resultsContainer.style.display = 'none';
            }
            
            // 原有的逻辑保持不变
            const menuId = this.getAttribute('data-menu');
            if (menuId) {
                selectMenu(menuId);
            }
        });
    });

    function changeFileType(type) {
        // 隐藏审核结果预览
        const resultsContainer = document.getElementById('reviewResultsContainer');
        if (resultsContainer) {
            resultsContainer.style.display = 'none';
        }
        
        // 继续执行原有逻辑
        currentFileType = type;
        const fileTypeSelect = document.getElementById('fileTypeSelect');
        fileTypeSelect.value = type;
        updateAcceptedFileTypes();
    }

    // 为文件类型选择按钮添加事件监听器
    function selectMenu(menuId) {
        // 关闭侧边栏（小屏幕）
        document.querySelector('.sidebar').classList.remove('open');
        
        // 隐藏审核结果预览
        const resultsContainer = document.getElementById('reviewResultsContainer');
        if (resultsContainer) {
            resultsContainer.style.display = 'none';
        }
    }
}); 